/**
 * @author:linjiye
 * @date: 2025/1/5
 * @desc:
 **/

import {ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState} from 'react'
import {useRouter} from "expo-router";
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FormTitle from "@/components/FormTitle";
import {Flex, Toast} from "@ant-design/react-native";
import FcButton from "@/components/FcButton";
import FcBtnScrollTab from "@/components/FcBtnScrollTab";
import FcTextInput from "@/components/FcTextInput";
import NoData from "@/components/NoData";
import FcModal from "@/components/FcModal";
import {useQueryListByUserQuery} from "@/store/api/keywordExplosion/keywordExplosionApi";
import {
    useAddGroupMutation,
    useGetItemListQuery,
    useGetParentListQuery
} from "@/store/api/aiOriginality/aiOriginalityApi";
import Loading from "@/components/Loading";
import {useDispatch, useSelector} from "react-redux";
import {set_pageRouterParams} from "@/store/reducer/aiFeeding/aiFeedingSlice";
import FcSearch from "@/components/FcSearch";
import KeywordHighlighter from "@/components/KeywordHighlighter";

type Props = {}

const index = (props: Props) => {
    const router = useRouter();
    const dispatch = useDispatch();
    let p = useSelector(state => state.aiFeeding.pageRouterParams)


    const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
    const [typeList, setTypeList] = useState([
        {
            name: '全部',
            id: '',
        },{
            name: '提供产品',
            id: 1,
        }, {
            name: '提供服务',
            id: 2
        }, {
            name: '经营场景',
            id: 3
        }
    ])
    const [typeId, setTypeId] = useState(typeList[0]?.id)
    const [productGroupItem, setProductGroupItem] = useState({})
    const [productNameItem, setProductNameItem] = useState({})
    const [groupList, setGroupList] = useState([])
    const [groupIndex, setGroupIndex] = useState(0)
    const [productList, setProductList] = useState([])

    const [searchText, setSearchText] = useState('')


    const [isAdd,setIsAdd] = useState(false)
    const [typeList1, setTypeList1] = useState([
        {
            name: '提供产品',
            id: 1,
        },{
            name: '提供服务',
            id: 2,
        },{
            name: '经营场景',
            id: 3,
        }
    ])
    const [typeId1, setTypeId1] = useState(typeList[0]?.id)
    const [productName, setProductName] = useState('')


    const {data:groupResData,isSuccess:groupSuccess, refetch:groupRefetch}= useGetParentListQuery?.({
        types: typeId,
        name: ''
    })
    const {data:productResData,isSuccess:productSuccess, refetch:productRefetch,isLoading}= useGetItemListQuery?.({
        parentId: productGroupItem?.id,
        name: searchText,
        types: typeId
    })
    const [addGroupFun] = useAddGroupMutation()

    useEffect(() => {
        if(p.val) {
            setTypeId('')
            handleProduct({
                id: '',title: '全部'
            })
            handleGroupClickTab(p.val,p.groupIndex)
        }
    }, [p]);

    useEffect(() => {
        // if (groupResData || groupSuccess) {
        let list = groupResData?.result || []
        let newList = list.map((item, index) => {
            return {
                ...item,
                title: item.name+'('+item.count+')'
            }
        })
        let allCount = list.reduce((acc, { count = 0 }) => acc + count, 0)
        setGroupList([{
            id: '',
            title: `全部(${allCount})`
        }, ...newList])
        // }
        if (productSuccess) {
            setProductList(productResData.result || [])
            // setProductNameItem(productResData.result[0])
            // getProfitModelInfoFun(productResData.result[0].id)
        }
    }, [groupSuccess,groupResData,productSuccess,productResData]);

    function getScrollBodyInfo({height}) {
        setPageScrollBodyH(height)
    }

    const handleProduct = (val) => {
        setTypeId(val.id)
        setGroupIndex(0)
        setGroupList([])
        setProductGroupItem({
            id: '',title: '全部'
        })

        setTimeout(() => {
            productRefetch()
        },500)
    }



    const handleType = (val) => {
        setTypeId1(val.id)
    }

    const handleGroupClickTab = (val,index) => {
        console.log(val, index);
        setProductList( [])
        setGroupIndex(index)
        setProductGroupItem(val)
        productRefetch()
    }

    const handleAddGroup = () => {
        addGroupFun({
            name: productName,
            parentId: productGroupItem.id,
            type: typeId1
        }).then(res => {
            if (res?.data?.code === 200) {
                setIsAdd(false)
                productRefetch()
                Toast.info('新增成功')
            }
        })
    }

    function goGroupList() {
        router.push('/aiFeeding/groupList')
        dispatch(set_pageRouterParams({
            pathname: `/aiFeeding/groupList`,
            pageName: 'aiFeeding',
        }))
    }

    function takeSearch() {
        router.push('/search')
        dispatch(set_pageRouterParams({
            pathname: `/aiFeeding/groupList`,
            pageName: 'aiFeeding',
            searchList: [],
            params: {
                typeId: typeId,
                groupData: productGroupItem,
            },
        }))
    }
    
    return (
        <PageScrollView
            viewType={'card'}
            isTransparentTab
            getPageScrollBodyInfo={getScrollBodyInfo}
            pageTab={
                <PageTabBar
                    style={{marginVertical: 10}}
                    title={'AI 私有化资料投喂'}
                    right={
                        <TouchableOpacity style={styles.tabBar_btn_wrap} onPress={() => {
                            setIsAdd(true)
                            setTypeId1('')
                            setProductName('')
                        }}>
                            <Text style={styles.tabBar_btn}>新增产品</Text>
                        </TouchableOpacity>
                    }
                />
            }
        >
            <View style={[styles.container]}>
                <FormTitle style={{paddingHorizontal: 16}} isLeftIcon title='选择类目' />
                <Flex wrap='wrap' style={styles.type_menu}>
                    {typeList?.map((item, index) =>
                        <View key={index} style={[styles.type_menu_item_box]}>
                            {/*<FcButton*/}
                            {/*    onClick={() => handleProduct(item)}*/}
                            {/*    type={typeId === item.id ? 'txtJBAndBkJB' : 'default'}*/}
                            {/*    style={[styles.type_menu_item]}*/}
                            {/*    itemStyle={{width: '100%', height: '100%', borderRadius: 7.5,paddingHorizontal: 0}}*/}
                            {/*    textName={item.name} borderWidth={1}></FcButton>*/}
                            <FcButton
                                onClick={() => handleProduct(item)}
                                type={typeId === item.id ? 'txtBK' : 'default'}
                                style={[styles.type_menu_item]}
                                itemStyle={{width: '100%', height: '100%'}}
                                textName={item.name} borderWidth={1}></FcButton>
                        </View>
                    )}
                </Flex>
                <View  style={{paddingHorizontal: 16}}>
                    <FormTitle isLeftIcon title='分组列表' />
                    <FcBtnScrollTab style={{marginLeft: -6,marginBottom: 20}} tabList={groupList} tabIndex={groupIndex} onClickMenuMore={() => goGroupList()}  onTabClick={handleGroupClickTab}/>
                    <FormTitle isLeftIcon title='产品名称' right={
                        <TouchableOpacity onPress={() => router.push(`/aiFeeding/editProductName?categoryId=${typeId}`)}>
                            <Text style={{fontSize: 12,color: '#2856FF',backgroundColor: '#F1F2F4'}}>编辑</Text>
                        </TouchableOpacity>
                    } />
                    {/*<FcTextInput type='search' text={searchText} placeholder={'请输入要搜索的内容'} onChangeText={setSearchText}*/}
                    {/*             height={40} onClick={takeSearch}/>*/}
                    <FcSearch style={{marginHorizontal: 0}} searchText={searchText} onSearch={(val) => setSearchText(val)}/>

                    {!isLoading &&
                        <>
                            {productList?.map((item, index) => (
                                <TouchableOpacity style={styles.item_wrap} key={index} onPress={() => router.push('/aiFeeding/details?id='+item.id+'&name='+item.name)}>
                                    <Text style={styles.item_text} numberOfLines={1} ellipsizeMode="tail">
                                        <KeywordHighlighter
                                            text={item.name}
                                            keywords={searchText}
                                            textStyle={{color: 'rgba(0, 0, 0, 0.9)', fontSize: 15}}
                                            textHeightLightStyle={{color: '#2856FF'}}
                                        />
                                    </Text>
                                    <Text style={{ fontFamily: 'FcIconFont',fontSize: 20,color: 'rgba(0,0,0,0.3)' }}>&#xe609;</Text>
                                </TouchableOpacity>
                            ))}

                            {productList?.length <= 0 &&
                                <View style={{
                                    flexDirection: 'column',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    paddingTop: 60,
                                    paddingBottom: 120
                                }}>
                                    <NoData hintText='暂无产品名称'/>
                                    <FcButton
                                        onClick={() => {
                                            setIsAdd(true)
                                            setTypeId1('')
                                            setProductName('')
                                        }}
                                        type='BjJB'
                                        colors={['#6989FF', '#C65EFD']}
                                        style={{width: 74, height: 32, justifyContent: 'center'}}
                                        itemStyle={{borderRadius: 8}}
                                        textName='去新增'></FcButton>
                                </View>
                            }
                        </>
                    }

                    {isLoading && <Loading style={{height: 300}}/>}
                </View>
            </View>

            <FcModal
                isOpen={isAdd}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsAdd(false)}
                style={styles.modal_default}
                titleText={'新增产品'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsAdd(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => handleAddGroup(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <View style={{paddingBottom: 20}}>
                    <FormTitle style={{paddingTop: 0}} isLeftIcon title='选择类目' />
                    <Flex wrap='wrap' style={styles.type_menu1}>
                        {typeList1?.map((item, index) =>
                            <View style={styles.type_menu_item1_box} key={index}>
                                <FcButton
                                    onClick={() => handleType(item)}
                                    type={typeId1 === item.id ? 'txtBK' : 'default'}
                                    style={[styles.type_menu_item1]}
                                    itemStyle={{width: '100%', height: '100%'}}
                                    textName={item.name} borderWidth={1}></FcButton>
                            </View>
                        )}
                    </Flex>
                    <FcTextInput text={productName} placeholder={'请输入产品名称'}
                                 onChangeText={setProductName}
                                 height={58}/>
                </View>
            </FcModal>
        </PageScrollView>
    )
}

export default index

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // backgroundColor: 'white',
    },
    tabBar_btn_wrap: {
        width: 64,
        height: 28,
        display: 'flex',
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: 'white',
        borderRadius: 8,
    },
    tabBar_btn: {
        fontSize: 14,
        color: '#2856FF',
    },
    type_menu: {
        display: "flex",
        flexWrap: "wrap",
        flexDirection: "row",
        paddingHorizontal: 12,
        marginBottom: 12
    },
    type_menu_item_box: {
        width: '25%',
        height: 40,
        marginBottom: 8
    },
    type_menu_item: {
        height: 40,
        lineHeight: 40,
        borderRadius: 8,
        marginHorizontal: 4,
        flex: 1,
    },
    item_wrap: {
        height: 56,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderBottomColor: '#f6f6f6',
        borderBottomWidth: 0.5,
    },
    item_text: {
        fontSize: 15,
        color: 'rgba(0,0,0,0.9)',
        flex: 1
    },
    modal_default: {
        width: 280,
        borderBottomRightRadius: 12,
        borderBottomLeftRadius: 12,
    },

    type_menu1: {
        display: "flex",
        flexWrap: "wrap",
        flexDirection: "row",
        marginLeft: -3,
        marginBottom: 16
    },
    type_menu_item1_box: {
        width: '33.33%',
        height: 40,
        marginBottom: 6
    },
    type_menu_item1: {
        height: 40,
        lineHeight: 40,
        borderRadius: 8,
        marginHorizontal: 3,
        flex: 1,
    },
})